package org.lztvn.elearning.controllers;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;
import org.lztvn.elearning.entities.User;
import org.lztvn.elearning.service.IUserService;
import org.lztvn.elearning.unityclass.FacebookAvarta;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.Connection;
import org.springframework.social.facebook.api.Facebook;
import org.springframework.social.facebook.api.FacebookProfile;
import org.springframework.social.facebook.connect.FacebookConnectionFactory;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.OAuth2Operations;
import org.springframework.social.oauth2.OAuth2Parameters;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
@Controller
@SessionAttributes("userFLogin")
public class FacebookController extends AppController{
	@Autowired
	IUserService serviceUser;
	private static final String SCOPE = "email,user_about_me,user_birthday";
	private static final String REDIRECT_URI = "http://localhost:8080/elearning/loginFaceBook";
	private static final String CLIENT_ID = "1385334085068747";
	private static final String APP_SECRET = "630f430324bf90287289a0b24642e36d";
	private FacebookConnectionFactory facebookConnectionFactory;
	@RequestMapping(value="/connect",method=RequestMethod.GET)
	public void facebookLogin(HttpServletRequest request,
			HttpServletResponse response){
		facebookConnectionFactory =
				new FacebookConnectionFactory(CLIENT_ID, APP_SECRET);
		OAuth2Operations oauthOperations = facebookConnectionFactory.getOAuthOperations();
		OAuth2Parameters params = new OAuth2Parameters();
		params.setScope(SCOPE);
		params.setRedirectUri(REDIRECT_URI);
		String authorizeUrl = oauthOperations.buildAuthorizeUrl(params);
		try {
			response.sendRedirect(authorizeUrl);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// upon receiving the callback from the provider:
		//String authorizationCode="";
		//AccessGrant accessGrant = oauthOperations.exchangeForAccess(authorizationCode, "https://my-callback-url", null);
		//Connection<Facebook> connection = connectionFactory.createConnection(accessGrant);
	}
	@RequestMapping(value="/loginFaceBook",method=RequestMethod.GET)
	public String facebookCallback(@RequestParam("code") String code, HttpServletRequest request,HttpServletResponse response, Model model){
		OAuth2Operations oauthOperations = 
				facebookConnectionFactory.getOAuthOperations();
		AccessGrant accessGrant = oauthOperations.exchangeForAccess(code, REDIRECT_URI, null);
		Connection<Facebook> connection = facebookConnectionFactory.createConnection(accessGrant);
		Facebook facebook = connection.getApi();
		FacebookProfile profile = facebook.userOperations().getUserProfile();
		User userFacebook = new User();
		DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); 
		try {
			userFacebook.setBirthdayDate(df.parse(profile.getBirthday()));
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		serviceUser.getUserByUsername(profile.getUsername());
		User user = serviceUser.getUserByUsername(profile.getEmail());
		if(user==null){
			userFacebook.setLastName(profile.getLastName());
			userFacebook.setUsername(profile.getEmail());;
			userFacebook.setFirstName(profile.getFirstName());
			userFacebook.setEmail(profile.getEmail());
			userFacebook.setPassword("lzt-elearning-2015");
			userFacebook.setActive(true);
			userFacebook.setAddress("Not update yet");
			userFacebook.setFromSocial("facebook");
			userFacebook.setDescription("Not update yet");
			try {
				String facebookImage = this.readJsonFromUrl(connection.getImageUrl()+"?redirect=false").data.url;
				URL url = new URL(facebookImage);
				BufferedImage  image = ImageIO.read(url);
				String fileName = UUID.randomUUID()+".jpg";
				ImageIO.write(image,"jpg",new File(request.getSession().getServletContext().getRealPath("/resources/images/front/")+"/"+fileName));
				userFacebook.setPhoto(fileName);
			} catch (IOException e) {
				e.printStackTrace(); 
			}
			serviceUser.addUser(userFacebook);
			user = serviceUser.getUserByUsername(profile.getEmail());
		}
		model.addAttribute("userFLogin", user);
		return "redirect:/viewUser?id="+user.getIdUser();
	}
	private  String readAll(Reader rd) throws IOException {
		StringBuilder sb = new StringBuilder();
		int cp;
		while ((cp = rd.read()) != -1) {
			sb.append((char) cp);
		}
		return sb.toString();
	}
	public  FacebookAvarta readJsonFromUrl(String url) throws IOException {
		InputStream is = new URL(url).openStream();
		try {
			BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
			String jsonText = readAll(rd);
			ObjectMapper mapper = new ObjectMapper();
			FacebookAvarta result = mapper.readValue(jsonText, FacebookAvarta.class);
			return result;
		} finally {
			is.close();
		}
	}

}
